﻿// Custom section

	    var map = null;
	    var uZoom = null;
	    var uCenter = null;
	    var oCenter = null;
	    var uPoint = null;
	    var uDetails = null;
	    var spot = null;
	    var mm = null;
	    var tooltip = false;
	    var smMapH = 250;
	    var smMapW = 250;
	    var lgMapH = null;
	    var lgMapW = null;
	    var polys = new Array();
	    var actW = {In:{},Ex:{}};
	    var actIn = 0.1;
	    var actBounds = null;
	    
		function load() {
            if (GBrowserIsCompatible()) {
                map = new GMap2($("map"));
                //removeCopyMessage();
                map.enableScrollWheelZoom();
                map.addControl(new GSmallMapControl());
				map.addControl(new GMapTypeControl());
				GEvent.addListener(map, "click", restoreMap);
                geocoder = new GClientGeocoder();
                map.setCenter(new GLatLng(geo.lat, geo.lng), geo.zoom);
                mm = new GMarkerManager(map, {borderPadding:1});
                $("loading").style.left = ($("map").getLeft() + 225) + "px";
                $("loading").style.top = ($("map").getTop() + 200) + "px";
                buildSquare();
                loadCities();
                loadEvents();
                lgMapH = $("map").getStyle('height').toInt();
	            lgMapW = $("map").getStyle('width').toInt();
	    	}
	    }
	    
	    function staticEventLoad(selLong, selLat, selIcon) {
	        loadCities();
	        if (selLong != 0 && selLat != 0) {
	            $("eventmap").style.display = "block";
                map = new GMap2($("eventmap"));
                map.addControl(new GMapTypeControl());
                var pt = new GLatLng(selLat, selLong);
                map.setCenter(pt, 15);
                var marker = new GMarker(pt, {icon: createPin(selIcon)});
                map.addOverlay(marker);
	        }
	    }
	    
	    function buildSquare() {
	        actW.In.D = map.getBounds().getSouthWest().lat();
	        actW.In.L = map.getBounds().getSouthWest().lng();
	        actW.In.U = map.getBounds().getNorthEast().lat();
	        actW.In.R = map.getBounds().getNorthEast().lng();
	        actW.Ex.D = actW.In.D - (actW.In.U - actW.In.D) * actIn;
	        actW.Ex.L = actW.In.L + (actW.In.L - actW.In.R) * actIn;
	        actW.Ex.U = actW.In.U + (actW.In.U - actW.In.D) * actIn;
	        actW.Ex.R = actW.In.R - (actW.In.L - actW.In.R) * actIn;
	        var pts = [];
	        pts[0] = new GLatLng(actW.Ex.U, actW.Ex.L);
	        pts[1] = new GLatLng(actW.Ex.U, actW.Ex.R);
	        pts[2] = new GLatLng(actW.Ex.D, actW.Ex.R);
	        pts[3] = new GLatLng(actW.Ex.D, actW.Ex.L);
	        pts[4] = pts[0];
	        var polygon = new GPolygon(pts, "#FF0000", 3, 1, "#FFFF00", 0);
	        actBounds = new GLatLngBounds(pts[3], pts[1]);
	        map.addOverlay(polygon);
	    }
	    
	    function loadCities() {
	        TopNavActivate();
	        $each(locs, function(loc, key){
                var option = new Element('option', {value: loc[4] + "/" + loc[1], innerText: HTMLindent(loc[3]) + loc[1]}).injectInside('getLocation');
                option.text = HTMLindent(loc[3]) + loc[1];
                if (map != null) {
                    if (loc[4] + "/" + loc[1] == geo.path) {
                        $("getLocation").selectedIndex = key;
                    }
                    var latlng = new GLatLng(loc[5], loc[6]);
                    if (!actBounds.contains(latlng)) {
                        var marker = new GMarker(latlng, {icon: createPin("radar")});
                        GEvent.addListener(marker, "click", function() {
                            location.href = (loc[4] + "/" + loc[1]).replace(/ /g, "_") + ".aspx";
                        });
                        GEvent.addListener(marker, "mouseover", function() {
                            $("areaname").style.top = (map.fromLatLngToContainerPixel(latlng).y + $("map").getPosition().y - 40) + "px";
                            $("areaname").style.left = (map.fromLatLngToContainerPixel(latlng).x + $("map").getPosition().x) + "px";
                            $("areaname").style.display = "block";
                            $("areaname").innerHTML = loc[1];
                        });
                        GEvent.addListener(marker, "mouseout", function() {
                            $("areaname").style.display = "none";
                        });
                        mm.addMarker(marker, loc[8], (loc[9] == 0) ? 15 : loc[7] - 1);
                        mm.refresh();
                    }
                 }
            });
            $("getLocation").addEvent("change", function (){
		        location.href = $("getLocation")[$("getLocation").selectedIndex].value.replace(/ /g, "_") + ".aspx";
	        });
	    }
	    
	    function loadBorders() {
	         $each(geo.areas, function(value, key){
                var pts = [];
                $each(value.poly, function(pt, i){
                    pts[i] = new GLatLng(pt[1], pt[0]);
                });
                var polygon = new GPolygon(pts, "#000000", 1, 1, "#FFFF00", 0.3);
                map.addOverlay(polygon);
            });
	    }
	    
	    function changeCenter() {
	        noCenter = true;
	        restoreMap(true);
	        oCenter = new GLatLng(cities[$("getLocation").value][1], cities[$("getLocation").value][2]);
	        uZoom = cities[$("getLocation").value][5];
	        map.setCenter(oCenter, uZoom);
	    }
	    
	    function loadEvents() {
	        $("loading").style.display = "block";
	        restoreMap(true);
	        ew = new EWindow(map, E_STYLE_7);
            map.addOverlay(ew);
	        new Ajax("/ajax_ret.aspx?per=" + $("getPeriod").value + "&U=" + actW.Ex.U + "&D=" + actW.Ex.D + "&L=" + actW.Ex.L + "&R=" + actW.Ex.R, {method: "get",
                onComplete: function(request) {
                    $("loading").style.display = "none";
                    cArray = Json.evaluate(request.substr(0, request.length - 1) + "]");
                    $("sidenews").innerHTML = "";
                    for(i = 0; i < cArray.length; i++) {
                        var point = new GLatLng(cArray[i][2], cArray[i][1]);
                        mm.addMarker(createMarker(point, cArray[i]), 10, 17);
                        if (i < 5) {
                            $("sidenews").innerHTML += "<h4><a href=\"/" + cArray[i][0] + ".aspx\">" + cArray[i][3] + "</a></h4>"
                        }
                    };
                   mm.refresh();
                   showTooltip();
                }
            }).request();
	    }
        
        function loadNews(nid) {
            oCenter = map.getCenter();
            new Fx.Styles('map', {duration:500, onComplete: function(request) {
                    $('article').style.display = "block";
				    map.checkResize();
				    uZoom = map.getZoom();
				    uCenter = uPoint.getPoint();
				    map.setCenter(uCenter, 15);
				    ew.hide();
				    pin = new GIcon();
                    pin.image = "/images/spot.png";
                    pin.iconSize = new GSize(29, 15);
                    pin.iconAnchor = new GPoint(14, 9);
                    spot = new GMarker(uCenter, {icon: pin});
                    map.addOverlay(spot);
                    $("mapmessage").style.display = "block";
                    $("leavemessage").style.display = "block";
                    $("readcomment").href = "/" + nid + ".aspx#messages"
                    $("leavecomment").href = "/" + nid + ".aspx#form"
                    $("iconslegend").style.display = "none";
			    }
            }).custom({'width': smMapW, 'height': smMapH});
            new Ajax("/ajax_ret.aspx?id=" + nid, {method: "get",
                onComplete: function(request) {
                    $('article').innerHTML = "<h3>" + uDetails[3] + "</h3><div id=\"topnewstime\">" + uDetails[5] + "</div>" + request;
                }
            }).request();
        }
        
	    function restoreMap(clMap) {
	        if ($("map").style.height == smMapH + "px") {
	            map.removeOverlay(spot);
	            $("article").style.display = "none";
	            $("article").innerHTML = "Loading...";
	            $("mapmessage").style.display = "none";
	            $("leavemessage").style.display = "none";
                $("iconslegend").style.display = "block";
	            new Fx.Styles('map', {duration:500, onComplete: function(request) {
                        map.checkResize();
                        map.setCenter(oCenter, uZoom);
                        if (clMap != null) {
                            ew.openOnMarker(uPoint, infoBox());
                        }
                    }
                }).custom({'width': lgMapW, 'height': lgMapH});
	        }
	    }
	    
	    function infoBox() {
	        return      '<a href="javascript:ew.hide()">' +
	                        '<img id="closeinf" title="Close the EWindow" src="/images/eclose.gif" border=0></a>' +
                        '</a>' +
                    '<i>' + uDetails[5] + '</i>. ' + uDetails[3] + ' [<a href="javascript:loadNews(' + uDetails[0] + ')">more</a>]';
	    }
	    
        //function createMarker(pt, pid, ptitle, ptype, plong, plat) {
        function createMarker(pt, p) {
            var marker = new GMarker(pt, {icon: createPin(p[4])});
            GEvent.addListener(marker, "click", function() {
                restoreMap(null);
                uPoint = marker;
                uDetails = p;
                ew.openOnMarker(marker, infoBox());
            });
            return marker;
         }
        
        function createPin(pname) {
            pin = new GIcon();
            pin.image = "/images/pin_" + pname +".gif";
            pin.iconSize = new GSize(15, 20);
            pin.iconAnchor = new GPoint(7, 20);
            pin.shadow = "/images/pin_shadow.png";
            pin.shadowSize = new GSize(20, 20);
            pin.infoWindowAnchor = new GPoint(8, 20);
            return pin;
        }
        
        function showTooltip() {
            if ($("tooltip").innerHTML.length > 0 && tooltip) {
                $("tooltip").style.left = (document.body.clientWidth / 2 + 80) + "px";
                new Fx.Style($("tooltip"), 'opacity').set(0);
                $("tooltip").style.display = "block";
                new Fx.Style($("tooltip"), 'opacity', {duration: 1200}).custom(0, 1);
            }
        }
        
        function closeTooltip() {
            $("tooltip").style.display = "none";
            tooltip = false;
        }
        
        function HTMLindent(lev) {
            var ind = "";
            for (i = 1; i <= lev; i++) {
                ind += " > ";
            }
            return ind;
        }
        
        function TopNavActivate() {
            var spans = $("menu").getChildren();
            $each(spans, function(item, key){
                if (item.getChildren().length == 2) {
                    var subm = item.getChildren()[1];
                    subm.style.top = item.getCoordinates().bottom + "px";
                    subm.style.left = item.getCoordinates().left + "px";
                    item.addEvent("mouseover", function (){
		                subm.style.display = "block";
	                });
	                item.addEvent("mouseout", function (){
		                subm.style.display = "none";
	                });
                }
            });
        }
        
        function removeCopyMessage() {
            var css = "@namespace url(http://www.w3.org/1999/xhtml); #map>div:first-child+div>* {display:none !important;}";
            if (typeof GM_addStyle != "undefined") {
                GM_addStyle(css);
            }
            else if (typeof addStyle != "undefined") {
                addStyle(css);
            }
            else {
                var heads = document.getElementsByTagName("head");
                if (heads.length > 0) {
                    var node = document.createElement("style");
                    node.type = "text/css";
                    node.appendChild(document.createTextNode(css));
                    heads[0].appendChild(node); 
                }
            }
        }
        
// EWindow section

// Version 0.0  Initial version 
// Version 0.1  10/10/2006 Added E_STYLE_7 
// Version 0.2  17/05/2007 Added .isHidden() and .supportsHide()
// Version 0.3  14/09/2007 added .zindex()


      function EStyle(stemImage, stemSize, boxClass, boxOffset) {
        this.stemImage = stemImage;
        this.stemSize = stemSize;
        this.boxClass = boxClass;
        this.boxOffset = boxOffset;
        //this.border = border;
        
        // Known fudge factors are:
        // Firefox (1.0.6 and 1.5)    5, -1
        // IE 6.0                     0, -1
        // Opera 8.54                 3, -1
        // Opera 9 prev               4, -1
        // Netscape (7.2, 8.0)        5, -1
        // Safari                     5, -1        
        
        var agent = navigator.userAgent.toLowerCase();
        
        var fudge = 0;  // assume Netscape if no match found
       
        if (agent.indexOf("opera") > -1) {
          fudge = 0;
        }   
        if (agent.indexOf("firefox") > -1) {
          fudge = 0;
        }   
        if (agent.indexOf("safari") > -1) {
          fudge = 0;
        }   
        if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){
          fudge = 0;
        }
        this.fudge = fudge;
      }
      
      var E_STYLE_7 = new EStyle("/images/stem.png", new GSize(22,19),  "estyle2", new GPoint(-7,18));

      function EWindow(map, estyle) {
        // parameters
        this.map = map;
        this.estyle = estyle;
        // internal variables
        this.visible = false;
        // browser - specific variables
        this.ie = false;
        var agent = navigator.userAgent.toLowerCase();
        if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){ this.ie = true} else {this.ie = false}
      } 
      
      EWindow.prototype = new GOverlay();

      EWindow.prototype.initialize = function(map) {
        var div1 = document.createElement("div");
        div1.style.position = "absolute";
        map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div1);
        var div2 = document.createElement("div");
        div2.style.position = "absolute";
        div2.style.width = this.estyle.stemSize.width+"px";
        map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div2);
        this.div1 = div1;
        this.div2 = div2;
      }

      EWindow.prototype.openOnMap = function(point, html, offset) {
        this.offset = offset||new GPoint(0,0);
        this.point = point;
        this.div1.innerHTML = '<div id="ewindow">' + html + '</div>';
        if (this.ie && this.estyle.stemImage.toLowerCase().indexOf(".png")>-1) {
          var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+this.estyle.stemImage+"', sizingMethod='scale');";
          this.div2.innerHTML = '<div style="height:' +this.estyle.stemSize.height+ 'px; width:'+this.estyle.stemSize.width+'px; ' +loader+ '" ></div>';
        } else {
          this.div2.innerHTML = '<img src="' + this.estyle.stemImage + '" width="' + this.estyle.stemSize.width +'" height="' + this.estyle.stemSize.height +'">';
        }
        var z = GOverlay.getZIndex(this.point.lat());
        this.div1.style.zIndex = z;
        this.div2.style.zIndex = z+1;
        this.visible = true;
        this.show();
        this.redraw(true);
		var apt = getAbsPos(this.div1, 'top');
		var apl = getAbsPos(this.div1, 'left');
		var div1w = this.div1.offsetWidth;
		if (apt < 5) {map.panBy(new GSize(0, 5 - apt))};
		if (apl < 5) {map.panBy(new GSize(5 - apl, 0))};
		if (apl + div1w > 495) {map.panBy(new GSize(498 - apl - div1w, 0))};
      }
      
      EWindow.prototype.openOnMarker = function(marker,html) {
        var vx = marker.getIcon().iconAnchor.x - marker.getIcon().infoWindowAnchor.x;
        var vy = marker.getIcon().iconAnchor.y - marker.getIcon().infoWindowAnchor.y + 6;
        this.openOnMap(marker.getPoint(), html, new GPoint(vx,vy));
      }

      EWindow.prototype.redraw = function(force) {
        if (!this.visible) {return;}
        var p = this.map.fromLatLngToDivPixel(this.point);
        this.div2.style.left   = (p.x + this.offset.x) + "px";
        this.div2.style.bottom = (-p.y + this.offset.y -this.estyle.fudge) + "px";
		this.div1.style.left   = (p.x + this.offset.x + this.estyle.boxOffset.x) + "px";
		var apl = getAbsPos(this.div1, 'left')
		if (apl > 285) {
			this.div1.style.left = (parseInt(this.div1.style.left) - ((apl > 450) ? 160 : (apl - 285))) + 'px';
		}
        this.div1.style.bottom = (-p.y + this.offset.y + this.estyle.boxOffset.y) + "px";
      }
	  
	  function getAbsPos( o, tl ) {
		var val = 0;
		while ( o.id != 'map' ) {
		  val += parseInt( ( tl == 'top' ) ? o.offsetTop : o.offsetLeft );
		  o = o.parentNode;
		}
		return val;
	  }

      EWindow.prototype.remove = function() {
        this.div1.parentNode.removeChild(this.div1);
        this.div2.parentNode.removeChild(this.div2);
        this.visible = false;
      }

      EWindow.prototype.copy = function() {
        return new EWindow(this.map, this.estyle);
      }

      EWindow.prototype.show = function() {
        this.div1.style.display="";
        this.div2.style.display="";
        this.visible = true;
      }
      
      EWindow.prototype.hide = function() {
        this.div1.style.display="none";
        this.div2.style.display="none";
        this.visible = false;
      }
      
      EWindow.prototype.isHidden = function() {
        return !this.visible;
      }
      
      EWindow.prototype.supportsHide = function() {
        return true;
      }

      EWindow.prototype.zindex = function(zin) {
        var z = GOverlay.getZIndex(this.point.lat());
        this.div1.style.zIndex = z+zin;
        this.div2.style.zIndex = z+1+zin;
      }
